package com.zzyl.nursing.WsConfig;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 *实现
 *@Author zhu
 *@Date 2025/10/29 10:54
 */
@Slf4j
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocket {
    private static Map<String, Session> sessionMap = new HashMap<>();

    /**
     * 连接时候触发
     * @param sid
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("sid") String sid, Session session) {
        log.info("连接成功，ID：{}", sid);
        sessionMap.put(sid, session);
    }

    /**
     * 关闭时候触发
     * @param sid
     * @param session
     */
    @OnClose
    public void onclose(@PathParam("sid") String sid, Session session) {
        log.info("关闭成功，ID：{}", sid);
        sessionMap.remove(sid, session);
    }

    /**
     * 通信发生错误
     * @param sid
     * @param session
     */
    @OnError
    public void onerror(@PathParam("sid") String sid, Session session, Throwable throwable) {
        log.info("错误，ID：{}", sid);
        throwable.printStackTrace();
    }

    /**
     * 服务端接受消息
     * @param sid
     * @param session
     */
    @OnMessage
    public void onmessage(@PathParam("sid") String sid, Session session, String message) {
        log.info("接收到消息，ID：{}，信息：{}", sid, message);
    }

    /**
     * 服务端发送消息，需要用到定时任务
     */
    public void sendMessageToAll(String sid, String message) {
        Collection<Session> values = sessionMap.values();
        if (!CollectionUtils.isEmpty(values)) {
            values.forEach(x -> {
                try {
                    x.getBasicRemote().sendText(message);
                    log.info("会话{}，发送了消息到客户端，消息内容：{}", sid, message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
